package com.weirong.smartvault.backservice.util.chart;

import com.weirong.smartvault.common.tools.spring.context.SpringContextUtil;
import com.weirong.smartvault.backservice.util.statistics.Statistics;
import com.weirong.smartvault.backservice.util.statistics.StatisticsType;
import com.weirong.smartvault.backservice.util.common.DateUtil;
import com.weirong.smartvault.dao.ForeignCurrencyTypeRepository;
import com.weirong.smartvault.entity.ForeignCurrencyType;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

/**
 * 于2017/12/22由 KFEB4 创建 .
 */
public class ChartStockDetail {
    private static ForeignCurrencyTypeRepository foreignCurrencyTypeRepository = SpringContextUtil.getBean(ForeignCurrencyTypeRepository.class);

    public static ChartOption buildOption(String date) throws ParseException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Date d = DateUtil.getMonthDate(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH);
        Integer monthDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);


        ChartOption option = new ChartOption();

        option.title.text = date+" 月度库存数据";

        for (ForeignCurrencyType foreignCurrencyType : foreignCurrencyTypeRepository.findAll()) {
            option.legend.data.add(foreignCurrencyType.getName());
        }
        ChartOption.XAxis xAxis = new ChartOption.XAxis();
        option.xAxis.add(xAxis);
        for (int i = 0; i < monthDays; i++) {
            xAxis.data.add(String.valueOf(i+1));
        }

        for (String type : option.legend.data) {
            ChartOption.Series series = new ChartOption.Series();
            option.series.add(series);

            ChartOption.Series.MakePoint.Type maxType = new ChartOption.Series.MakePoint.Type();
            series.makePoint.data.add(maxType);
            maxType.name = "最大值";
            maxType.type = "max";
            ChartOption.Series.MakePoint.Type minType = new ChartOption.Series.MakePoint.Type();
            series.makePoint.data.add(minType);
            minType.name = "最小值";
            minType.type = "min";
            ChartOption.Series.MakeLine.Type averageType = new ChartOption.Series.MakeLine.Type();
            series.makeLine.data.add(averageType);
            averageType.name = "平均值";
            averageType.type = "average";

            series.name = type;
            series.type = "bar";
            String typeCode = foreignCurrencyTypeRepository.getByName(type).getCode();
            for (int i = 0; i < monthDays; i++) {
                series.data.add((float) Statistics.getValue(StatisticsType.STOCKBYDAT, typeCode, year, month,i));
            }
        }
        return option;
    }
}
